package codeTop;

import java.util.AbstractMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

public class q662 {
    public int widthOfBinaryTree(TreeNode root) {
        Queue<Map.Entry<TreeNode,Integer>> queue = new LinkedList<>();
        queue.offer(new AbstractMap.SimpleEntry<>(root,0));
        int res = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            int left = 0;
            for (int i = 0; i < size; i++) {
                Map.Entry<TreeNode, Integer> poll = queue.poll();
                TreeNode node = poll.getKey();
                Integer value = poll.getValue();
                if (i == 0) {
                    left = value;
                }
                if (i == size - 1) {
                    res = Math.max(res,value-left+1);
                }
                if (node.left != null) {
                    queue.offer(new AbstractMap.SimpleEntry<>(node.left,2*value));
                }
                if (node.right != null) {
                    queue.offer(new AbstractMap.SimpleEntry<>(node.right,2*value+1));
                }
            }
        }
        return res;
    }
}
